package com.mflex.mwms.activity;

import android.content.Intent;
import android.os.Bundle;
import android.view.KeyEvent;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;

import com.google.gson.reflect.TypeToken;
import com.mflex.mwms.R;
import com.mflex.mwms.adapter.TeslaCompareAdapter;
import com.mflex.mwms.adapter.TeslaCompareDetailAdapter;
import com.mflex.mwms.model.CustomApiResult;
import com.mflex.mwms.model.Task;
import com.mflex.mwms.model.TaskDetail;
import com.mflex.mwms.model.TeslaComapreInfo;
import com.mflex.mwms.model.TeslaCustomCompareRequest;
import com.mflex.mwms.model.enumeration.CustomCompare;
import com.mflex.mwms.utils.MMKVUtils;
import com.mflex.mwms.utils.MessageUtils;
import com.mflex.mwms.utils.XToastUtils;
import com.xuexiang.xhttp2.XHttp;
import com.xuexiang.xhttp2.callback.CallBackProxy;
import com.xuexiang.xhttp2.callback.SimpleCallBack;
import com.xuexiang.xhttp2.exception.ApiException;
import com.xuexiang.xui.utils.WidgetUtils;
import com.xuexiang.xui.widget.dialog.MiniLoadingDialog;
import com.xuexiang.xutil.common.StringUtils;
import com.xuexiang.xutil.net.JsonUtil;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class TudaTongCompareDetailActivity extends BaseActivity {
    @BindView(R.id.stv_TaskNo)
    EditText stvTaskNo;
//    @BindView(R.id.stv_CustomPallet)
//    EditText stvCustomPallet;
    @BindView(R.id.stv_BoxNumber)
    EditText stvBoxNumber;
    @BindView(R.id.stv_CustomBoxNumber)
    EditText stvCustomBoxNumber;
    @BindView(R.id.button_clear)
    Button buttonClear;

    @BindView(R.id.button_submit)
    Button buttonSubmit;

    @BindView(R.id.lvTaskList)
    ListView lvTaskList;

    MiniLoadingDialog mMiniLoadingDialog;

    private Task task;
    private String develiverNo;
    private String customPNPallet;
    private String customPNBox;
//    private int qty;
//
//    private int scanQty;

    List<TeslaComapreInfo> teslaComapreInfoList;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_tuda_tong_compare_detail);

        ButterKnife.bind(this);
        mMiniLoadingDialog = WidgetUtils.getMiniLoadingDialog(this, "加载...");


//        stvCustomPallet.setOnKeyListener(this);
        stvBoxNumber.setOnKeyListener(this);
        stvCustomBoxNumber.setOnKeyListener(this);
        buttonClear.setOnClickListener(this);
        buttonSubmit.setOnClickListener(this);

        teslaComapreInfoList = new ArrayList<>();

        stvBoxNumber.postDelayed(new Runnable() {
            @Override
            public void run() {
                stvBoxNumber.requestFocus();
            }
        }, 200);

        Intent intent = getIntent();
        Type listType = new TypeToken<Task>() {
        }.getType();
        task = (Task) JsonUtil.fromJson(intent.getStringExtra("task"), listType);
        develiverNo = intent.getStringExtra("develiverNo");

        stvTaskNo.setText(task.getTaskNo());

        for (TaskDetail taskDetail : task.getTaskDetails()) {
            TeslaComapreInfo teslaComapreInfo = new TeslaComapreInfo();
            teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
            teslaComapreInfo.setBoxNumber(taskDetail.getDetailName());
            teslaComapreInfo.setPn(taskDetail.getPN());
            teslaComapreInfo.setTaskNo(task.getTaskNo());
            teslaComapreInfoList.add(teslaComapreInfo);
        }

        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(TudaTongCompareDetailActivity.this, teslaComapreInfoList);
        lvTaskList.setAdapter(teslaCompareDetailAdapter);

//        qty = 0;
//        scanQty = 0;
    }

    @Override
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.button_clear:
                clearButtonMd(view);
                break;
            case R.id.button_submit:
                SubmitButtonMd(view);
                break;
            default:
                break;
        }
    }

    @Override
    public boolean onKey(View view, int i, KeyEvent keyEvent) {
        if (keyEvent.getAction() == KeyEvent.ACTION_DOWN && (i == 66 || i == 61)) {
            switch (view.getId()) {
//                case R.id.stv_CustomPallet:
//                    checkCustomPallet(view);
//                    break;
                case R.id.stv_BoxNumber:
                    checkBoxNumber(view);
                    break;
                case R.id.stv_CustomBoxNumber:
                    checkCustomBoxNumber(view);
                    break;
                default:
                    break;
            }
        }
        return false;
    }

//    private void checkCustomPallet(View view) {
//        if (StringUtils.isEmpty(stvCustomPallet.getText().toString())) {
//            stvCustomPallet.setText("");
//            stvCustomPallet.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    stvCustomPallet.requestFocus();
//                }
//            }, 200);
//            return;
//        }
//
//        String[] customPalletNoList = stvCustomPallet.getText().toString().split("@");
//        if (customPalletNoList.length != 9) {
////            XToastUtils.error("客户栈板标格式不正确1", 3000);
//            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "客户栈板标格式不正确");
//            stvCustomPallet.setText("");
//            stvCustomPallet.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    stvCustomPallet.requestFocus();
//                }
//            }, 200);
//            return;
//        }
//        customPNPallet = customPalletNoList[4];
//
//
//        if (!StringUtils.isInteger(customPalletNoList[6])) {
////            XToastUtils.error("客户栈板标格式不正确5", 3000);
//            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "客户栈板标格式不正确");
//            stvCustomPallet.setText("");
//            stvCustomPallet.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    stvCustomBoxNumber.requestFocus();
//                }
//            }, 200);
//            return;
//        }
//        qty = Integer.parseInt(customPalletNoList[7]);
//
//        if (!StringUtils.equals(task.getStockoutDetails().get(0).getCOPN(), customPNPallet)) {
////            XToastUtils.error("栈板标与COPN不匹配", 3000);
//            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "栈板标与COPN不匹配");
//            stvCustomPallet.setText("");
//            stvCustomPallet.postDelayed(new Runnable() {
//                @Override
//                public void run() {
//                    stvCustomPallet.requestFocus();
//                }
//            }, 200);
//            return;
//        }
//        stvCustomPallet.setFocusable(false);
//        stvCustomBoxNumber.postDelayed(new Runnable() {
//            @Override
//            public void run() {
//                stvCustomBoxNumber.requestFocus();
//            }
//        }, 200);
//    }

    private void checkBoxNumber(View view) {
        boolean flag = false;

        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString())) {
                flag = true;
                break;
            }
        }
        if (!flag) {
            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "该箱不在任务列表中");
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
            return;
        }
        boolean flag2 = false;

        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString()) && teslaComapreInfo.checked) {
                flag2 = true;
                break;
            }
        }
        if (flag2) {
//            XToastUtils.error("该箱已扫描", 3000);
            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "该箱已扫描");
            stvBoxNumber.setText("");
            stvBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvBoxNumber.requestFocus();
                }
            }, 200);
            return;
        }
    }

    private void checkCustomBoxNumber(View view) {
        if (StringUtils.isEmpty(stvCustomBoxNumber.getText().toString())) {
            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            },200);
            return;
        }
//        String[] customBoxList = stvCustomBoxNumber.getText().toString().split(":");
//        if (customBoxList.length < 3) {
//            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "客户箱标格式不正确");
//            stvCustomBoxNumber.setText("");
//            stvCustomBoxNumber.requestFocus();
//            return;
//        }
        boolean flag = false;
        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (StringUtils.equals(stvCustomBoxNumber.getText().toString(), teslaComapreInfo.getCustomBoxNumber())) {
                flag = true;
                break;
            }
        }
        if (flag) {
            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "客户箱标已在列表中");
            stvCustomBoxNumber.setText("");

            stvCustomBoxNumber.postDelayed(new Runnable() {
                @Override
                public void run() {
                    stvCustomBoxNumber.requestFocus();
                }
            }, 200);
        }

        XHttp.get("api/Comparison/CheckCustomNumber")
                .params("CustomNumber", stvCustomBoxNumber.getText().toString())
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();

                        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
                            if (StringUtils.equals(teslaComapreInfo.getBoxNumber(), stvBoxNumber.getText().toString())) {
                                teslaComapreInfo.setCustomBoxNumber(stvCustomBoxNumber.getText().toString());
                                teslaComapreInfo.setDeveliverNo(develiverNo);
                                teslaComapreInfo.setTaskNo(task.getTaskNo());
                                teslaComapreInfo.setMark(String.valueOf(CustomCompare.TUDATONG.getCode()));
                                teslaComapreInfo.setChecked(true);
                            }
                        }

                        Collections.sort(teslaComapreInfoList, new Comparator<TeslaComapreInfo>() {
                            @Override
                            public int compare(TeslaComapreInfo t0, TeslaComapreInfo t1) {
                                if (!t0.isChecked() && t1.isChecked()) {
                                    return -1;
                                }
                                return 0;
                            }
                        });
                        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(TudaTongCompareDetailActivity.this, teslaComapreInfoList);
                        lvTaskList.setAdapter(teslaCompareDetailAdapter);
                        stvBoxNumber.setText("");
                        stvCustomBoxNumber.setText("");
                        stvBoxNumber.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                stvBoxNumber.requestFocus();
                            }
                        },200);
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        stvCustomBoxNumber.setText("");
                        stvCustomBoxNumber.requestFocus();
                        MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, e);
                    }
                }) {
                });
    }

    private void clearButtonMd(View v) {
        customPNPallet = "";
        stvCustomBoxNumber.setText("");
        stvBoxNumber.setText("");
        teslaComapreInfoList = new ArrayList<>();
        for (TaskDetail taskDetail : task.getTaskDetails()) {
            TeslaComapreInfo teslaComapreInfo = new TeslaComapreInfo();
            teslaComapreInfo.setMark(String.valueOf(CustomCompare.CATLXIDIAN.getCode()));
            teslaComapreInfo.setBoxNumber(taskDetail.getDetailName());
            teslaComapreInfo.setPn(taskDetail.getPN());
            teslaComapreInfo.setTaskNo(task.getTaskNo());
            teslaComapreInfoList.add(teslaComapreInfo);
        }
        TeslaCompareDetailAdapter teslaCompareDetailAdapter = new TeslaCompareDetailAdapter(TudaTongCompareDetailActivity.this, teslaComapreInfoList);
        lvTaskList.setAdapter(teslaCompareDetailAdapter);
        XToastUtils.success("重置成功！");
    }

    private void SubmitButtonMd(View view) {
        boolean flag = false;
        for (TeslaComapreInfo teslaComapreInfo : teslaComapreInfoList) {
            if (!teslaComapreInfo.isChecked()) {
                flag = true;
            }
        }
        if (flag) {
//            XToastUtils.error("没有比对完成！",3000);
            MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, "没有比对完成");
            return;
        }

        TeslaCustomCompareRequest request = new TeslaCustomCompareRequest();
        request.setTeslaCustomCompares(teslaComapreInfoList);
        mMiniLoadingDialog.show();
        XHttp.post("api/Comparison/CustomLabelCompare")
                .upJson(JsonUtil.toJson(request))
                .syncRequest(false)
                .onMainThread(true)
                .accessToken(true)
                .timeOut(120000)
                .execute(new CallBackProxy<CustomApiResult<String>, String>(new SimpleCallBack<String>() {

                    @Override
                    public void onSuccess(String response) {
                        mMiniLoadingDialog.dismiss();
                        XToastUtils.success("比对成功", 2500);

                        setResult(0);
                        finish();
                    }

                    @Override
                    public void onError(ApiException e) {
                        mMiniLoadingDialog.dismiss();
                        MessageUtils.errorMsgAndVoice(TudaTongCompareDetailActivity.this, e);
                    }
                }) {
                });
    }
}